package org.cloudy.memory.util;

public class ByteUtil {	
	public static int readInt ( byte[] b, int pos ) {
		int ch1 = b[pos];
		int ch2 = b[pos + 1];
		int ch3 = b[pos + 2];
		int ch4 = b[pos + 3];
		return ( ( ( ch4 & 0xff ) << 24 ) | ( ( ch3 & 0xff ) << 16 ) | ( ( ch2 & 0xff ) << 8 ) | ( ch1 & 0xff ) ) ;		
	}
	
	public static int readShort ( byte[] b, int pos ) {
		int ch1 = b[pos];
		int ch2 = b[pos + 1];
		return ( ( ( ch2 & 0xff ) << 8 ) | ( ch1 & 0xff ) ) ;		
	}	
	
	public static String readString ( byte[] b, int pos, int len ) {
		return new String ( b, pos, len ).replaceAll(String.valueOf((char)0), "") ;
	}	
	
	public static int readLong ( byte[] b, int pos ) {
		int ch1 = b[pos];
		int ch2 = b[pos + 1];
		int ch3 = b[pos + 2];
		int ch4 = b[pos + 3];
		int ch5 = b[pos + 4];
		int ch6 = b[pos + 5];
		int ch7 = b[pos + 6];
		int ch8 = b[pos + 7];
		
		return ( ( ( ( ch8 & 0xff ) << 56 ) | ( ch7 & 0xff ) << 48 ) | ( ( ch6 & 0xff ) << 40 ) | ( ( ch5 & 0xff ) << 32 ) | ( ( ch4 & 0xff ) << 24 ) | ( ( ch3 & 0xff ) << 16 ) | ( ( ch2 & 0xff ) << 8 ) | ( ch1 & 0xff ) ) ;
	}	
	
	public static byte[] writeString ( String value, int len ) {
		byte[] buf = new byte[ len ] ;
		System.arraycopy ( value.getBytes (), 0, buf, 0, value.getBytes ().length ) ;
 		return buf ;
	}	
	
	public static byte[] writeLong ( int value ) {
		byte[] b = new byte[8];
		b[7] = ( byte )( value >> 56 ) ;
		b[6] = ( byte )( value >> 48 ) ;
		b[5] = ( byte )( value >> 40 ) ;
		b[4] = ( byte )( value >> 32 ) ;
		b[3] = ( byte )( value >> 24 ) ;
		b[2] = ( byte )( value >> 16 ) ;
		b[1] = ( byte )( value >> 8 ) ;
		b[0] = ( byte )( value ) ;
		return b ;
	}		
	
	public static byte[] writeInt ( int value ) {
		byte[] b = new byte[4] ;
		b[3] = ( byte )( value >> 24 ) ;
		b[2] = ( byte )( value >> 16 ) ;
		b[1] = ( byte )( value >> 8 ) ;
		b[0] = ( byte )( value ) ;
		return b ;
	}	
	
	public static byte[] writeShort ( short value ) {
		byte[] buf = new byte[2] ;
		buf[1] = ( byte )( value >> 8 ) ;
		buf[0] = ( byte )( value ) ;
		return buf ;
	}	
}